﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Data;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.DAL;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.BLL
{
    public partial class SysPayDiscountConfigBLL : BaseBLL<SysPayDiscountConfigBLL>
    {
        #region 默认方法
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(SysPayDiscountConfig model)
        {
            return SysPayDiscountConfigDAL.Instance.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(SysPayDiscountConfig model)
        {
            return SysPayDiscountConfigDAL.Instance.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int Id)
        {
            return SysPayDiscountConfigDAL.Instance.Delete(Id);
        }
        /// <summary>
        /// 批量删除一批数据
        /// </summary>
        public bool DeleteList(string Idlist)
        {
            return SysPayDiscountConfigDAL.Instance.DeleteList(Idlist);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>  
        public SysPayDiscountConfig GetModel(int Id)
        {
            var ds = SysPayDiscountConfigDAL.Instance.GetModel(Id);
            return ds == null ? null : ServicesHelper.DataSetToIList<SysPayDiscountConfig>(ds).ToList()[0];
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<SysPayDiscountConfig> GetModelList(string strWhere = null)
        {
            var ds = SysPayDiscountConfigDAL.Instance.GetList(strWhere);
            return ServicesHelper.DataSetToIList<SysPayDiscountConfig>(ds).ToList();
        }
        #endregion

        #region 扩展方法

        public SysPayDiscountConfig GetModel(decimal minPayDiscount, decimal maxPayDiscount)
        {
            var ds = SysPayDiscountConfigDAL.Instance.GetModel(minPayDiscount, maxPayDiscount);
            return ds == null ? null : ServicesHelper.DataSetToIList<SysPayDiscountConfig>(ds).ToList()[0];
        }
        /// <summary>
        ///     获得分页数据列表
        /// </summary>
        public TableDataViewDto<ViewSysPayDiscountConfigDto> GetPagingList(int draw, int pageIndex, int pageSize, string searchKeyWord, string colOrder)
        {
            try
            {
                int totalCount = 0;
                List<ViewSysPayDiscountConfigDto> list = SysPayDiscountConfigDAL.Instance.GetPagingList(pageIndex, pageSize, searchKeyWord, colOrder, ref totalCount);
                list.ForEach(a =>
                {
                    a.Action =
                        "<a class='btn btn-warning' href='javascript:;' onclick=updateData(" + a.Id + ");>修改</a> " +
                        "<a class='btn btn-danger' href='javascript:;' onclick=deleteData(" + a.Id + ");>删除</a>";
                });
                var returnDataList = new TableDataViewDto<ViewSysPayDiscountConfigDto>
                {
                    data = list,
                    draw = draw,
                    recordsFiltered = totalCount,
                    recordsTotal = totalCount
                };

                return returnDataList;
            }
            catch (Exception ex)
            {
                _fileLog.Error(" GetPagingList | Exception: " + ex);
                return null;
            }
        }

        /// <summary>
        /// 获取立减金额
        /// </summary>
        /// <param name="consumerId">用户id</param>
        /// <param name="maxDiscoutPrice">订单总金额-最大立减金额</param>
        /// <returns>立减金额</returns>
        public Double GetRandomPayDiscount(int consumerId, decimal maxDiscoutPrice)
        {
            var consumer = ConsumerBLL.Instance.GetModel(consumerId);
            if (consumer == null)
            {
                return 0;
            }
            var discountBase = DiscountBaseBLL.Instance.GetModelList(string.Format(" UserType={0}", (int)(consumer.ShopId > 0 ? CommonEnum.UserType.WateStan : CommonEnum.UserType.Platform))).FirstOrDefault();
            if (discountBase == null)
            {
                discountBase = DiscountBaseBLL.Instance.GetModelList(string.Format(" UserType={0}", (int)CommonEnum.UserType.NoLimit)).FirstOrDefault();
                if (discountBase == null || discountBase.ConsumerTotalTimes <= 0)
                {
                    return 0;
                }
            }
            var timeSpanCount = TimeHelper.GetTimeRangeByTimeSpanType((TimeSpanType)discountBase.TimeSpanType, discountBase.TimeSpanCount);
            //用户已立减次数
            var discountTimesList = DiscountRecordBLL.Instance.GetModelList("ConsumerId=" + consumer.Id + " and AddTime>='" + timeSpanCount[0] + "' and AddTime<='" + timeSpanCount[1] + "'");
            if (discountBase.ConsumerTotalTimes <= discountTimesList.Count)
            {
                return 0;
            }
            decimal lastDiscountMoney = -1;
            if (discountTimesList.Count > 0)
            {
                lastDiscountMoney = discountTimesList[discountTimesList.Count - 1].DiscountPrice;
            }
            //立减概率计算
            var discountTimesProbability = DiscountTimesProbabilityBLL.Instance.GetModelList(string.Format(" SerialNum={0} and DiscountBaseId={1}", discountTimesList.Count + 1, discountBase.Id)).FirstOrDefault();
            if (discountTimesProbability == null)
            {
                return 0;
            }
            var sysPayDiscountConfigList = this.GetModelList(string.Format("DiscountBaseId={0}", discountBase.Id));
            if (sysPayDiscountConfigList.Count == 0)
            {
                return 0;
            }
            if (lastDiscountMoney != -1)
            {
                sysPayDiscountConfigList.RemoveAll(l => l.MinPayDiscount > lastDiscountMoney);
            }
            if (sysPayDiscountConfigList.Count == 0)
            {
                return 0;
            }
            double payDiscount = 0;
            var discountConfig = CalcRandomConfig(sysPayDiscountConfigList, discountTimesProbability.DiscountPercent);
            if (discountConfig != null)
            {
                //立减金额不能高于统计时间内的上一次立减金额
                if (lastDiscountMoney != -1 && discountConfig.MaxPayDiscount > lastDiscountMoney)
                {
                    discountConfig.MaxPayDiscount = lastDiscountMoney;
                }
                //立减最大金额不等大于订单总金额
                discountConfig.MaxPayDiscount = discountConfig.MaxPayDiscount < maxDiscoutPrice
                    ? discountConfig.MaxPayDiscount
                    : maxDiscoutPrice;
                var random = new Random();
                payDiscount =
                    Math.Round(
                        random.NextDouble() * (double)(discountConfig.MaxPayDiscount - discountConfig.MinPayDiscount) +
                        (double)discountConfig.MinPayDiscount, 2);
            }
            return payDiscount;
        }

        /// <summary>
        /// 获取立减金额-额度
        /// </summary>
        /// <param name="sysPayDiscountConfigList">立减配置</param>
        /// <param name="discountPercent">中奖百分比(几率)</param>
        private SysPayDiscountConfig CalcRandomConfig(List<SysPayDiscountConfig> sysPayDiscountConfigList, int discountPercent)
        {
            SysPayDiscountConfig discountConfig = null;
            var countRangeList = new List<List<int>>();
            //当前所有奖品总数累加和
            var currentAllTotalCount = 0;
            //计算奖品范围基数值
            foreach (var item in sysPayDiscountConfigList)
            {
                countRangeList.Add(new List<int>
                {
                    currentAllTotalCount + 1,
                    currentAllTotalCount + item.DiscountProbability
                });
                currentAllTotalCount += item.DiscountProbability;
            }
            //根据百分比重新计算随机基数
            var baseCount = int.Parse(Math.Ceiling(currentAllTotalCount / (discountPercent / 100.0)).ToString());
            //以所有奖品总数累加和为上限，1为下限，随机出一位数
            var randomNum = new Random().Next(1, baseCount + 1);
            //奖品序号
            int? awardIndex = null;
            for (var i = 0; i < countRangeList.Count; i++)
            {
                //判断随机数是否在某个范围基数内，奖品总数范围值越大，中奖几率越高
                if (countRangeList[i][0] <= randomNum && countRangeList[i][1] >= randomNum)
                {
                    //如果在范围内，则为奖品序号赋值
                    awardIndex = i;
                    break;
                }
            }
            if (awardIndex.HasValue)
            {
                //根据奖品序号取得奖品Id，并获取奖品信息返回
                discountConfig = sysPayDiscountConfigList[awardIndex.Value];
            }
            return discountConfig;
        }

        public bool DeleteByDiscountBaseId(int discountBaseId)
        {
            return SysPayDiscountConfigDAL.Instance.DeleteByDiscountBaseId(discountBaseId);
        }

        #endregion
    }
}